<template>
  <div class="top-bar-container">
    <van-nav-bar
      :left-text="props.leftText"
      :left-arrow="props.leftArrow"
      :title="title"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <!-- 父组件传入的结构，再插入到slot中 -->
      <template #right>
        <slot name="right">退出登录</slot>
      </template>
    </van-nav-bar>
  </div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/modules/user'
import { computed, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 路由器实例
const router = useRouter()

// 当前路由实例
const route = useRoute()

// 接受父组件传入的属性
const props = defineProps({
  leftText: {
    type: String,
    default: '返回上级',
  },
  leftArrow: {
    type: Boolean,
    default: true,
  },
  title: {
    type: String,
    default: '标题',
  },
})

// 标题
const title = computed(() => route.meta.title || props.title)

// 子组件向父组件传递事件
const emits = defineEmits<{
  (e: 'click-left', event: MouseEvent): void
  (e: 'click-right', event: MouseEvent): void
}>()

/**
 * 点击左侧按钮
 * @param e 点击事件
 */
const onClickLeft = (e: MouseEvent) => {
  // 父组件传入了点击事件，抛出自定义事件
  const hasListener = getCurrentInstance()?.vnode.props?.['onClickLeft']
  if (hasListener) {
    emits('click-left', e)
  } else {
    // 父组件没有传入点击事件，默认返回上一级
    // 判断是否有返回记录
    if (history.state.back) {
      router.back()
    } else {
      router.push('/')
    }
  }
}

/**
 * 点击右侧按钮
 * @param e 点击事件
 */
const onClickRight = async (e: MouseEvent) => {
  // 父组件传入了点击事件，抛出自定义事件
  const hasListener = getCurrentInstance()?.vnode.props?.['onClickRight']
  if (hasListener) {
    emits('click-right', e)
  } else {
    // 父组件没有传入点击事件，默认退出登录
    const { logout } = useUserStore()
    try {
      const res = await logout()
      console.log('退出登录成功', res)
      router.push('/login')
    } catch (error) {
      console.log(error)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-bar-container {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  :deep(.van-nav-bar) {
    // 右侧
    .van-nav-bar__right {
      color: var(--van-primary-color);
    }
  }
}
</style>
